<template>
  <div>
    <div v-if="creativeRequestDetailIndex == 0">
      <el-form ref="creativeRequestForm" :model="creativeRequestForm" label-width="150px"
               :rules="creativeRequestFormRules">
        <el-row :gutter="20">
          <el-col span="24">
            <el-form-item nameItemsDesc label="需求名称:" prop="nameItems">
              <el-select
                id="id-offer-componets-creativerequest-conmponents-request-edit-detail-nameItems"
                size="mini"
                clearable
                filterable
                multiple
                v-model="creativeRequestForm.nameItems.nation"
                :disabled="!userRole.optimize"
                placeholder="请选择地区"
                style="width: 15%"
              >
                <el-option
                  v-for="item in nationList"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictValue"
                >
                </el-option>
              </el-select>
              {{ '-' }}
              <el-select
                size="mini"
                clearable
                filterable
                multiple
                v-model="creativeRequestForm.nameItems.language"
                :disabled="!userRole.optimize"
                placeholder="请选择投放语言"
                style="width: 15%"
              >
                <el-option
                  v-for="item in languageList"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictValue"
                >
                </el-option>
              </el-select>
              {{ '-' }}
              <el-select
                id="id-offer-componets-creativerequest-conmponents-request-edit-detail-type"
                size="mini"
                clearable
                v-model="creativeRequestForm.nameItems.type"
                :disabled="!userRole.optimize"
                placeholder="请选择类型"
                style="width: 15%"
              >
                <el-option
                  v-for="item in requestNameType"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictValue"
                >
                </el-option>
              </el-select>
              {{ '-' }}
              <el-input id="id-offer-componets-creativerequest-conmponents-request-edit-detail-desc"
                        placeholder="请输入需求名称描述" :disabled=" !userRole.optimize"
                        v-model="creativeRequestForm.nameItems.desc" clearable size="mini"
                        style="width: 30%"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="需求方 :" prop="requester">
              <el-select
                id="id-offer-componets-creativerequest-conmponents-request-edit-detail-requester"
                disabled
                size="mini"
                :disabled="!userRole.optimize"
                v-model="creativeRequestForm.requester"
                filterable
                clearable
                placeholder="请选择"
                style="width: 70%">
                <el-option
                  v-for="(item, index) in optimizerList"
                  :key="index"
                  :value="item.id"
                  :label="item.realName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="媒体 :" prop="platform">
              <el-select
                id="id-offer-componets-creativerequest-conmponents-request-edit-detail-backToUploadPlatform"
                size="mini"
                multiple
                v-model="creativeRequestForm.platform"
                :disabled="!userRole.optimize"
                placeholder="请选择"
                style="width: 70%"
                @change="backToUploadPlatform"
              >
                <el-option
                  v-for="item in platformsList"
                  :key="item.dictKey"
                  :value="item.dictKey"
                  :label="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="交付日期 :" prop="expectedTime" style="padding-right: 10px">
              <el-date-picker
                style="width: 100%"
                size="mini"
                v-model="creativeRequestForm.expectedTime"
                :disabled="!userRole.optimize"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item label="设计师负责人 :" prop="designerManager">
              <el-select
                id="id-offer-componets-creativerequest-conmponents-request-edit-detail-designerManager"
                disabled
                size="mini"
                :disabled="!userRole.optimize"
                v-model="creativeRequestForm.designerManager"
                filterable
                clearable
                placeholder="请选择设计师负责人"
                style="width: 70%">
                <el-option
                  v-for="(item, index) in designerManagerList"
                  :key="index"
                  :value="item.id"
                  :label="item.realName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item prop="creativeType" label="素材类型 :">
              <el-checkbox-group size="mini" v-model="creativeRequestForm.creativeType" :disabled="!userRole.optimize">
                <el-checkbox
                  v-for="(item, index) in checkedCreativeTypeList"
                  :label="item.id"
                  :key="index"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col span="8">
            <el-form-item prop="urgency" label="紧急程度 :">
              <el-radio size="mini" v-model="creativeRequestForm.urgency" label="1" :disabled="!userRole.optimize"
              >紧急
              </el-radio>
              <el-radio size="mini" v-model="creativeRequestForm.urgency" label="0" :disabled="!userRole.optimize"
              >一般
              </el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-form ref="creativeRequestDetailForm" :model="creativeRequestDetailForm" label-width="150px"
             :rules="creativeRequestDetailFormRules">
      <div>
        <el-row class="checkRequestHistory" v-if="creativeRequestDetailIndex == 0">
          <el-col span="16" style="text-align: right;">
            <a @click="creativeRequestHistory(creativeRequestDetailIndex,creativeRequestDetail)">查看历史需求记录</a>
          </el-col>
          <el-col span="8" style="text-align: left;"
                  v-if="creativeRequestDetailIndex == 0 && userInfo.detail.tenantVariables['ENABLE_REQUEST_DETAIL_AUDIT'] == 'true'">
            <el-form-item prop="auditStatus" v-if="isDesignerManager"
                          :rules="creativeRequestDetailFormRules.auditStatus">
              <el-radio size="mini" v-model="creativeRequestDetailForm.auditStatus" label="1"
                        :disabled="!isDesignerManager">同意
              </el-radio>
              <el-radio size="mini" v-model="creativeRequestDetailForm.auditStatus" label="2"
                        :disabled="!isDesignerManager">拒绝
              </el-radio>
            </el-form-item>
            <span
              :style="'color: ' + findByProp(detailAuditStatus,creativeRequestDetailForm.auditStatus,'value','color')"
              v-else>需求内容审核状态：{{
                findByProp(detailAuditStatus, creativeRequestDetailForm.auditStatus, 'value', 'label')
              }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="16">
            <el-form-item label="需求内容 :" prop="content" :rules="creativeRequestDetailFormRules.content">
<!--              <el-input type="textarea" v-model="creativeRequestDetailForm.content" :autosize="{ minRows: 4 }"-->
<!--                        :readonly="!(creativeRequestDetailIndex == 0 && userRole.optimize)"></el-input>-->
<!--              <avue-ueditor v-model="creativeRequestDetailForm.content"-->
<!--                            v-bind="options"></avue-ueditor>-->
              <quill-editor style="height: 180px; margin-bottom: 40px" v-model="creativeRequestDetailForm.content" :options="editorOptions"></quill-editor>
            </el-form-item>
          </el-col>
          <el-col span="8" v-show="creativeRequestDetailForm.auditStatus == 2">
            <el-form-item label="拒绝描述 :" prop="auditComment" :rules="creativeRequestDetailFormRules.auditComment">
              <el-input id="id-offer-componets-creativerequest-conmponents-request-edit-detail-auditComment"
                        type="textarea" v-model="creativeRequestDetailForm.auditComment" :autosize="{ minRows: 4 }"
                        :readonly="!(creativeRequestDetailIndex == 0 && isDesignerManager)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="需求内容附件 :">
          <creative-upload ref="upload"
                           :mode="(creativeRequestDetailIndex == 0 && userRole.optimize)?'edit':'readonly'"
                           :init-file-list="getFileList(creativeRequestDetail)"
                           :file-list-change="handleAppendFileChange" :max="5"
                           :data="creativeRequestDetail"></creative-upload>
          </el-form-item>
        </el-row>
        <!-- 需求内容反显最新一条需求-->
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="素材数量 :" prop="creativeNum" :rules="creativeRequestDetailFormRules.creativeNum"
                          class="request_creativeNum">
              <el-input-number size="mini" style="width: 150px" :min="1"
                               :disabled="!(creativeRequestDetailIndex == 0 && userRole.optimize)"
                               v-model="creativeRequestDetailForm.creativeNum"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="选择参考素材 :">
            <div class="tabs_creative">
              <div @click="creativeTypeClick('creatives')"
                   :class="creativeDialogType === 'creatives' ? 'tags_true':'tags_false'"
                   style="width: 50%;border-right: 1px solid rgba(22, 132, 252, 100);cursor: pointer;border-radius: 10px 0 0 10px">
                素材库
              </div>
              <div @click="creativeTypeClick('originalCreatives')"
                   :class="creativeDialogType === 'originalCreatives' ? 'tags_true':'tags_false'"
                   style="width: 50%;cursor: pointer;border-radius: 0 10px 10px 0">原始参考素材
              </div>
            </div>
            <div>
              <!-- 素材库-->
              <div v-if="creativeDialogType === 'creatives' " label="素材库" name="creatives">
                <div class="refCreative">
                  <a @click="appendClick(creativeRequestDetailIndex)"
                     v-if="creativeRequestDetailIndex == 0 && userRole.optimize"><i
                    class="el-icon-zoom-in">添加</i></a>
                  <a @click="downloadCreative(creativeRequestDetail,'creative')" style="margin-left: 20px"><i
                    class="el-icon-download">下载</i></a>
                </div>
                <!-- 素材添加之后的素材回显到这里 -->
                <el-row :gutter="20" class="creative_list" style="margin: 0">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(creative, i) in creativeRequestDetail.creativeList"
                      :key="i"
                      class="el-upload-list__item is-ready"
                    >
                      <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                      <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>
                      <img
                        v-if="
                          creative.thumbnailUrl !== '-1' &&
                          creative.thumbnailUrl !== '-2'
                        "
                        class="el-upload-list__item-thumbnail creative"
                        :src="creative.thumbnailUrl"
                        alt=""
                        @click="detailCreative(creative,$event)" showdetail="true"
                      />
                      <span class="el-upload-list__item-actions" @click="detailCreative(creative,$event)"
                            showdetail="true">
                            <span
                              v-if="creativeRequestDetailIndex == 0 && userRole.optimize"
                              class="el-upload-list__item-delete"
                              @click="deleteCreative(creative, 'creativeList')"
                            >
                              <i class="el-icon-delete"></i>
                            </span>
                          </span>
                    </li>
                  </ul>
                </el-row>
              </div>
              <!--原始参考材料-->
              <div v-if="creativeDialogType === 'originalCreatives'" label="原始参考素材" name="originalCreatives">
                <div class="refCreative">
                  <a @click="appendClick(creativeRequestDetailIndex)"
                     v-if="creativeRequestDetailIndex == 0 && userRole.optimize"><i
                    class="el-icon-zoom-in">添加</i></a>
                  <a @click="handleOriginCreativeAdd(creativeRequestDetailIndex)" style="margin-left: 20px"
                     v-if="creativeRequestDetailIndex == 0 && userRole.optimize"><i class="el-icon-plus">自定义</i></a>
                  <a @click="downloadCreative(creativeRequestDetail,'originCreative')" style="margin-left: 20px"><i
                    class="el-icon-download">下载</i></a>
                </div>
                <el-row :gutter="20" class="creative_list" style="margin: 0">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(creative, i) in creativeRequestDetail.originalCreativeList"
                      :key="i"
                      class="el-upload-list__item is-ready"
                    >
                      <div v-if="creative.creativeUrl === '-1'">上传中</div>
                      <div v-if="creative.creativeUrl === '-2'">上传失败</div>
                      <img
                        v-if="
                          creative.creativeUrl !== '-1' &&
                          creative.creativeUrl !== '-2'
                        "
                        class="el-upload-list__item-thumbnail creative"
                        :src="creative.creativeUrl"
                        alt=""
                        @click="detailCreative(creative,$event)" showdetail="true"
                      />
                      <span class="el-upload-list__item-actions" @click="detailCreative(creative,$event)"
                            showdetail="true">
                        <span
                          v-if="creativeRequestDetailIndex == 0 && userRole.optimize"
                          class="el-upload-list__item-delete"
                          @click="
                            deleteCreative(creative, 'originalCreativeList')
                          "
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </li>
                  </ul>
                </el-row>
              </div>
              <!-- 被拒素材-->
              <div v-if="creativeDialogType === 'rejectedCreatives' && false" label="被拒素材" name="rejectedCreatives">
                <div class="refCreative" v-if="creativeRequestDetailIndex == 0 && userRole.optimize">
                  <a @click="appendClick(creativeRequestDetailIndex)">添加</a>
                </div>
                <el-row :gutter="20" class="creative_list" style="margin: 0">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(creative, i) in creativeRequestDetail.rejectedCreativeList"
                      :key="i"
                      class="el-upload-list__item is-ready"
                    >
                      <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                      <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>
                      <img
                        v-if="
                          creative.thumbnailUrl !== '-1' &&
                          creative.thumbnailUrl !== '-2'
                        "
                        class="el-upload-list__item-thumbnail creative"
                        :src="creative.thumbnailUrl"
                        alt=""
                        @click="detailCreative(creative,$event)" showdetail="true"
                      />
                      <span class="el-upload-list__item-actions" @click="detailCreative(creative,$event)"
                            showdetail="true">
                        <span
                          v-if="creativeRequestDetailIndex == 0 && userRole.optimize"
                          class="el-upload-list__item-delete"
                          @click="
                            deleteCreative(creative, 'rejectedCreativeList')
                          "
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </li>
                  </ul>
                </el-row>
              </div>
            </div>
          </el-form-item>
        </el-row>
      </div>
      <!--参考素材-->
      <creative-request-append :dialogVisible="appendDialogOpen" :title="creativeDialogType"
                               :index="creativeRequestDetailIndex"
                               @close-dialog="appendCloseDialog" @append-creatives="appendCreatives"
                               :existed-creative-ids="existedCreativeIds"
                               :creative-request-id="creativeRequestId" :offer-id="offerId" ref="childData"/>
      <div v-if="originCreativeAddDialogVisible">
        <origin-creative-add :dialogVisible="originCreativeAddDialogVisible"
                             @onClose="originCreativeAddOnClose"></origin-creative-add>
      </div>
      <!-- 素材详情-->
      <el-dialog :visible.sync="detailCreativeDialog" append-to-body top="0px;" :modal-append-to-body="false"
                 :close-on-click-modal="true"
                 :show-close="false" :before-close="closeDetailDialog" width="60%" class="creative-detail-list">
        <div style="text-align: center; width: 100%; height: 100%">
          <div slot="title" style="text-align: right">
            <el-button class="dialog-close" size="mini" icon="el-icon-close" @click="closeDetailDialog"
                       circle></el-button>
          </div>
          <img :src="detailCreativeUrl" v-show="detailType === 'image'"/>
          <video v-show="detailType === 'video'" ref="video" :src="detailCreativeUrl"
                 autoplay="autoplay" controls="controls" class="creative_edit"></video>
        </div>
      </el-dialog>
    </el-form>
    <!--需求历史记录-->
    <div v-if="historyDialog">
      <request-history :close-history="closeHistory" :creativeRequestDetail="historyCreativeRequestDetail"
                       :dialogVisible="historyDialog" :userRole="userRole"
      ></request-history>
    </div>
    <div id="downloadContent" style="display: none;"></div>
  </div>
</template>

<script>
import {
  getOfferDesigner,
  getOfferOptimizer,
  getOfferDesignerManager,
} from "@/api/offer/creativerequest";
import {getSysDictList} from "@/api/system/dict";
import {getDetail} from "@/api/business/offer";

import creativeUpload from "/src/components/beetles-upload/creative_upload";
import creativeRequestAppend from "../creativeRequestAppend";
import originCreativeAdd from "../originCreativeAdd";
import requestHistory from "./request-history";
import {mapGetters} from "vuex";
import {findArray, findByProp, findObject} from "@/util/util";
import func from "@/util/func";
import JSZip from "jszip";
import Moment from "moment";
import FileSaver from "file-saver"

export default {
  name: "request-edit-detail",
  components: {
    creativeUpload,
    creativeRequestAppend,
    originCreativeAdd,
    requestHistory,
  },
  data() {
    /**
     * 验证
     */
    let checkAuditStatsus = (rule, value, callback) => {
      if (this.isDesignerManager && value != 1 && value != 2) {
        return callback(new Error("请对需求内容进行审核"));
      } else {
        callback();
      }
    };

    let checkCreativeType = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (value.length === 0) {
          return callback(new Error("请选择素材类型"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //紧急程度
    let checkUrgency = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value) {
          return callback(new Error("请选择紧急程度"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //媒体
    let checkPlatform = (rule, value, callback) => {
      if (this.userRole.optimize || this.userRole.admin) {
        if (value === null || value.length === 0) {
          return callback(new Error("请选择媒体"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // //需求方
    // let checkRequester = (rule, value, callback) => {
    //   if (this.userRole.optimize) {
    //     if (!value) {
    //       return callback(new Error('请选择需求方'))
    //     } else {
    //       callback();
    //     }
    //   } else {
    //     callback();
    //   }
    // }
    //交付日期
    let checkExpectedTime = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value) {
          return callback(new Error("请选择期望时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //状态
    let checkStatus = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value && value !== 0) {
          return callback(new Error("请选择状态"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let validateNameItems = (rule, value, callback) => {
      if (value.desc == null || value.desc.trim() == '') {
        return callback(new Error('请输入需求名称描述'))
      } else {
        return callback();
      }
    };
    return {
      options: {
        customConfig: {},//wangEditor编辑的配置
      },
      findByProp: findByProp,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      creativeRequestForm: {
        name: '',
        nameItems: {
          nation: [],
          language: [],
          type: '',
          desc: '',
        },
        creativeType: [], //素材类型
        requester: null, //需求方
        designerManager: null, //设计师负责人
        expectedTime: null, //交付日期
        platform: [], //媒体
        urgency: '', //紧急程度
      },
      creativeRequestDetailForm: {
        auditStatus: '0',
        auditComment: '',
        content: "",
        creativeNum: 1,
      },
      checkedCreativeTypeList: [
        {id: "0", name: "图片"},
        {id: "1", name: "视频"},
      ],
      upload: {
        max: 5,
      },
      appendFileList: [],
      offerDetail: {},
      platformsList: [], // 媒体列表
      requestNameType: [],
      nationList: [],
      languageList: [],
      designerList: [], //设计师列表
      designerManagerList: [], //设计师负责人
      optimizerList: [], //优化师列表
      changeableStatusList: [
        {
          label: "待分配",
          value: "0",
        },
        {
          label: "制作中",
          value: "1",
        },
        {
          label: "待确认",
          value: "2",
        },
        {
          label: "已确认",
          value: "3",
        },
        {
          label: "需求待审核",
          value: "4",
        },
        {
          label: "需求被拒绝",
          value: "5",
        },
      ], //状态列表
      creativeRequestDetailFormRules: {
        content: [
          {required: true, message: '请输入需求内容', trigger: "change"},
        ],
        auditStatus: [
          {required: true, validator: checkAuditStatsus, trigger: "change"},
        ],
        auditComment: [
          {required: false, message: '请输入拒绝原因', trigger: "change"},
        ],
        creativeNum: [
          {required: true, message: '请输入素材数量', trigger: "change"},
        ],
      },
      creativeRequestFormRules: {
        nameItems: [{required: true, message: "请输入需求名称", trigger: "blur",}, {
          validator: validateNameItems,
          trigger: 'change'
        }],
        creativeType: [
          {required: true, validator: checkCreativeType, trigger: "change"},
        ],
        urgency: [
          {required: true, message: '请选择紧急程度', trigger: "change"},
        ],
        platform: [
          {
            required: true,
            validator: checkPlatform,
            trigger: "change",
          },
        ],
        requester: [
          {
            required: true,
            message: '请选择需求方',
            trigger: "change",
          },
        ],
        designerManager: [{required: true, message: '请选择设计师负责人', trigger: "change"}],
        expectedTime: [
          {required: true, validator: checkExpectedTime, trigger: "change"},
        ],
      },

      existedCreativeIds: '',
      appendDialogOpen: false, //参考素材弹窗开关
      creativeDialogType: "", //参考素材title
      index: "", //参考素材的下标
      originCreativeAddDialogVisible: false, //参考素材-原始参考素材-自定义开关
      detailCreativeDialog: false, //素材详情
      detailType: {}, //素材详情弹窗-素材类型
      detailCreativeUrl: "", //素材详情弹窗-素材URL
      detailAuditStatus: [
        {label: '待审核', value: 0, color: 'blue'},
        {label: '同意', value: 1, color: 'lawngreen'},
        {label: '拒绝', value: 2, color: 'orangered'},
      ],

      historyDialog: false,//需求历史记录弹窗
      historyCreativeRequestDetail: null,
      isSaving: false,
      editorOptions: {
        placeholder: '请输入内容',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              ['blockquote', 'code-block'], // 引用  代码块
              [{ header: 1 }, { header: 2 }], // 1、2 级标题
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              [{ script: 'sub' }, { script: 'super' }], // 上标/下标
              [{ indent: '-1' }, { indent: '+1' }], // 缩进
              [{ direction: 'rtl' }], // 文本方向
              // [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
              // [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
              // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
              // // [{ font: ['songti'] }], // 字体种类
              // [{ align: [] }], // 对齐方式
              ['clean'], // 清除文本格式
              ['image', 'video'] // 链接、图片、视频
            ]
          }
        },
      }
    };
  },
  props: {
    offerId: String,
    getPlatform: Function,
    title: String,
    userRole: Object,
    creativeRequestData: Object,
    creativeRequestDetail: Object,
    creativeRequestDetailIndex: Number,
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    isDesignerManager() {
      return (this.userRole.admin || this.userInfo.user_id == this.creativeRequestData.creativeRequest.designerManager);
    },
  },
  watch: {
    'creativeRequestDetailForm.auditStatus': {
      deep: true,
      handler(val) {
        this.creativeRequestDetailFormRules.auditComment.forEach((rule) => {
          rule.required = (val == 2);
        });
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    //初始化
    init() {
      //设计师
      getOfferDesigner(this.offerId).then((res) => {
        this.designerList = res.data.data;
      });
      //优化师
      getOfferOptimizer(this.offerId).then((res) => {
        this.optimizerList = res.data.data;
      });
      getOfferDesignerManager(this.offerId).then((res) => {
        this.designerManagerList = res.data.data;
      });
      //媒体
      getSysDictList("platforms,language,request_name_type,nation").then((map) => {
        this.languageList = map['language'];
        this.requestNameType = map['request_name_type'];
        this.nationList = map['nation'];
        this.platformsList = map['platforms'];
        this.creativeRequestForm.nameItems = this.parseRequestName(this.creativeRequestForm.name);
      });
      getDetail(this.offerId).then((res) => {
        this.offerDetail = res.data.data;
      });
      this.creativeRequestForm.name = this.creativeRequestData.creativeRequest.name;
      this.creativeRequestForm.nameItems = this.parseRequestName(this.creativeRequestForm.name);
      this.creativeRequestForm.creativeType = func.toList(this.creativeRequestData.creativeRequest.creativeType);
      this.creativeRequestForm.urgency = '' + this.creativeRequestData.creativeRequest.urgency;
      this.creativeRequestForm.expectedTime = this.creativeRequestData.creativeRequest.expectedTime;
      this.creativeRequestForm.designerManager = func.optimizeValue(this.creativeRequestData.creativeRequest.designerManager, -1, '');
      this.creativeRequestForm.platform = func.toList(this.creativeRequestData.creativeRequest.platform);
      this.creativeRequestForm.requester = this.creativeRequestData.creativeRequest.requester;

      this.creativeRequestDetailForm.auditStatus = '' + this.creativeRequestDetail.auditStatus;
      this.creativeRequestDetailForm.oldAuditStatus = this.creativeRequestDetail.auditStatus;
      this.creativeRequestDetailForm.auditComment = (this.creativeRequestDetailForm.auditStatus != 2) ? '' : this.creativeRequestDetail.auditComment;
      this.creativeRequestDetailForm.content = this.creativeRequestDetail.content;
      if (this.creativeRequestDetail.creativeNum != null && this.creativeRequestDetail.creativeNum != -1) {
        this.creativeRequestDetailForm.creativeNum = this.creativeRequestDetail.creativeNum;
      } else {
        this.creativeRequestDetailForm.creativeNum = 1;
      }

      this.creativeRequestDetail.activeName = 'creativeRequestDetail';
      this.creativeRequestDetail.itemActiveName = 'creatives';
      this.appendFileList = [];
      if (this.creativeRequestDetail.appendFiles != null && this.creativeRequestDetail.appendFiles.startsWith('[')) {
        this.appendFileList = JSON.parse(this.creativeRequestDetail.appendFiles);
      }
      this.creativeRequestFormRules.designerManager.forEach((rule) => {
        rule.required = (this.userInfo.detail.tenantVariables['ENABLE_REQUEST_DETAIL_AUDIT'] == 'true' && (this.userRole.optimize || this.userInfo.user_id == this.creativeRequestData.creativeRequest.createUser));
      });

      this.creativeTypeClick('creatives');
    },
    backToUploadPlatform(val) {
      this.getPlatform(val);
    },
    getFileList(creativeRequestDetail) {
      let fileList = [];
      this.appendFileList.forEach((appendFile) => {
        fileList.push({
          name: appendFile.filename,
          url: appendFile.fileUrl,
        })
      });
      return fileList;
    },
    handleAppendFileChange(data, file, type) {
      if (type == 'delete' && !file.uid) {
        for (let n = 0; n < this.appendFileList.length; n++) {
          if (this.appendFileList[n].fileUrl == file.url) {
            this.removeAppendFile(this.appendFileList[n], n);
            return;
          }
        }
      }
    },
    removeAppendFile(file, index) {
      this.appendFileList.splice(index, 1);
      this.creativeRequestDetail.appendFiles = JSON.stringify(this.appendFileList);
    },

    //参考素材
    /**
     * 获取素材
     */
    appendClick(index) {
      this.creativeDialogType = this.creativeRequestDetail.itemActiveName;
      this.appendDialogOpen = true;
      this.index = index;
      let childTitle = this.$refs.childData.title;
      this.existedCreativeIds = this.getExistedCreativeIds(childTitle, index);
      this.creativeRequestId = this.id;
    },
    /*
      关闭参考素材
     */
    appendCloseDialog() {
      this.appendDialogOpen = false;
    },

    /**
     * 获取已经有的素材id
     */
    getExistedCreativeIds(title, index) {
      let ids = [];
      if (title === "creatives") {
        let dataList = this.form[index].creativeList;
        for (let i in dataList) {
          ids.push(dataList[i].id);
        }
      } else if (title === "originalCreatives") {
        let dataList = this.form[index].originalCreativeList;
        for (let item in dataList) {
          ids.push(dataList[item].id);
        }
      } else if (title === "rejectedCreatives") {
        let dataList = this.form[index].rejectedCreativeList;
        for (let it in dataList) {
          ids.push(dataList[it].id);
        }
      }
      return ids.join(",");
    },
    /*
      添加参考素材
     */
    appendCreatives(creatives, title, index) {
      if (title === "creatives") {
        let dataList = this.creativeRequestDetail.creativeList;
        this.creativeRequestDetail.creativeList = dataList.concat(creatives);
      } else if (title === "originalCreatives") {
        let dataList = this.creativeRequestDetail.originalCreativeList;
        this.creativeRequestDetail.originalCreativeList = dataList.concat(creatives);
      } else if (title === "rejectedCreatives") {
        let dataList = this.creativeRequestDetail.rejectedCreativeList;
        this.creativeRequestDetail.rejectedCreativeList = dataList.concat(creatives);
      }
    },
    /**
     * 设置参考素材title
     */
    creativeTypeClick(tab) {
      this.creativeDialogType = tab;
      this.creativeRequestDetail.itemActiveName = tab
    },
    /*
      删除参考素材
     */
    deleteCreative(creative, prop) {
      let creativeIndex = findArray(this.creativeRequestDetail[prop], creative.id, 'id');
      if (creativeIndex != -1) {
        //this.deletedFinishedIds.push(creative.id)
        this.creativeRequestDetail[prop].splice(creativeIndex, 1)
      }
    },
    /**
     * 原始参考素材自定义素材
     */
    handleOriginCreativeAdd(index) {
      this.index = index;
      this.originCreativeAddDialogVisible = true;
    },
    /**
     * 原始参考素材关闭
     */
    originCreativeAddOnClose(originCreativeList) {
      if (originCreativeList != null) {
        this.appendCreatives(
          originCreativeList,
          "originalCreatives",
          this.index
        );
      }
      this.originCreativeAddDialogVisible = false;
    },

    //素材详情
    /*
      查看素材
     */
    detailCreative(row, event) {
      if (event == null || event.target.getAttribute('showdetail') != 'true') {
        return;
      }
      let creativeDetailInfo = this.getCreativeDetailInfo(row);
      if (!creativeDetailInfo) {
        return;
      }
      this.detailCreativeDialog = true;
      this.detailType = creativeDetailInfo.detailType;
      this.detailCreativeUrl = creativeDetailInfo.detailCreativeUrl;
    },
    /**
     * 判断素材类型
     */
    getCreativeDetailInfo(row) {
      let url = row.creativeUrl;
      if (!url) {
        url = row.link;
      }
      if (!url) {
        return null;
      }
      let div = url.indexOf('?');
      if (div != -1) {
        url = url.substring(0, div);
      }
      let type;
      let urlType = url.split(".")[url.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlType)) {
        type = "image";
      } else if (videoList.includes(urlType)) {
        type = "video";
      }
      return {detailType: type, detailCreativeUrl: url};
    },
    /**
     * 素材详情 关闭
     */
    closeDetailDialog() {
      this.detailCreativeDialog = false;
      this.$refs.video.pause();
    },
    /**
     * 表单验证
     */
    validateCreativeRequestDetailForm() {
      let flag = false;
      this.$refs.creativeRequestDetailForm.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
    // 下载参考素材
    downloadCreative(creativeRequestDetail,type) {
      let downloadIds = []
      if (type == 'creative') {
        // creativeRequestDetail.creativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.creativeList.length === 1) {
          this.downVideo(creativeRequestDetail.creativeList[0].creativeUrl)
        } else if (creativeRequestDetail.creativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.creativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (type == 'originCreative') {
        // creativeRequestDetail.originalCreativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.originalCreativeList.length === 1) {
          this.downVideo(creativeRequestDetail.originalCreativeList[0].creativeUrl)
        } else if (creativeRequestDetail.originalCreativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.originalCreativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (type == 'rejectedCreative') {
        // this.creativeRequestDetail.rejectedCreativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.rejectedCreativeList.length === 1) {
          this.downVideo(creativeRequestDetail.rejectedCreativeList[0].creativeUrl)
        } else if (creativeRequestDetail.rejectedCreativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.rejectedCreativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (downloadIds.length === 0) {
        this.$message({
          type: 'warning',
          message: '没有可下载的素材!'
        })

        return
      }
    },
    downloadUrlQiniu(url) {
      return new Promise((resolve, reject) => {
        if (!url.startsWith('http')) {
          return;
        }
        if (!url.startsWith('https')) {
          let urlArr = url.split("://")
          if (urlArr.length < 2) {
            return;
          }
          url = "https://" + urlArr[1]
        }
        fetch(url, {
          method: 'GET',
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
          }
        }).then(res => {
          resolve(res.blob())
        }).catch(err => {
          reject(err)
        })
      })
    },
    getAppendFileList() {
      try {
        return this.$refs.upload.getUploadFiles();
      } catch (error) {
        return null;
      }
    },
    saveInput() {
      if (this.creativeRequestDetailIndex == 0) {
        this.creativeRequestData.creativeRequest.creativeType = this.creativeRequestForm.creativeType.join(',');
        this.creativeRequestData.creativeRequest.platform = this.creativeRequestForm.platform.join(',');
        this.creativeRequestData.creativeRequest.requester = this.creativeRequestForm.requester;
        this.creativeRequestData.creativeRequest.expectedTime = this.creativeRequestForm.expectedTime;
        this.creativeRequestData.creativeRequest.designerManager = this.creativeRequestForm.designerManager;
        this.creativeRequestForm.name = this.toRequestName(this.creativeRequestForm.nameItems);
        this.creativeRequestData.creativeRequest.name = this.creativeRequestForm.name;
        this.creativeRequestData.creativeRequest.urgency = this.creativeRequestForm.urgency;

        this.creativeRequestDetail.auditStatus = this.creativeRequestDetailForm.auditStatus;
        if (this.creativeRequestDetailForm.auditStatus == 2) {
          this.creativeRequestDetail.auditComment = this.creativeRequestDetailForm.auditComment;
        }
        this.creativeRequestDetail.content = this.creativeRequestDetailForm.content;
        this.creativeRequestDetail.creativeNum = this.creativeRequestDetailForm.creativeNum;
      }
    },
    checkInput() {
      try {
        if (!this.$refs.upload.uploadCompleted()) {
          return "附件未上传完成！";
        }
      } catch (error) {
      }
      let finalMessage = null;
      let self = this;
      if (self.creativeRequestDetailIndex == 0) {
        self.$refs.creativeRequestForm.validate((valid) => {
          if (valid) {
            self.$refs.creativeRequestDetailForm.validate((valid) => {
              if (!valid) {
                finalMessage = "输入检查不通过！";
              }
            })
          } else {
            finalMessage = "输入检查不通过！";
          }
        });
      }
      return finalMessage;
    },
    creativeRequestHistory(index, item) {
      this.historyCreativeRequestDetail = item;
      this.historyDialog = true
    },
    closeHistory() {
      this.historyDialog = false
    },
    parseRequestName(name) {
      let result = {
        nation: [],
        language: [],
        type: '',
        desc: name,
      };
      if (name == null || this.nationList.length == 0 || this.languageList.length == 0 || this.requestNameType.length == 0) {
        return result;
      } else {
        let divStart = 0;
        let divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          let itemList = (item != '') ? item.split('&') : [];
          if (itemList.length > 0 && findObject(this.nationList, itemList[0], 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.nation = itemList;
            result.desc = name;
          }
        }
        divStart = 0;
        divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          let itemList = (item != '') ? item.split('&') : [];
          if (itemList.length > 0 && findObject(this.languageList, itemList[0], 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.language = itemList;
            result.desc = name;
          }
        }
        divStart = 0;
        divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          if (findObject(this.requestNameType, item, 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.type = item;
            result.desc = name;
          }
        }
        return result;
      }
    },
    toRequestName(nameItems) {
      if (nameItems == null) {
        return '';
      } else {
        let nameItemList = [];
        if (nameItems.nation != null && nameItems.nation.length > 0) {
          nameItemList.push(nameItems.nation.join('&'));
        }
        if (nameItems.language != null && nameItems.language.length > 0) {
          nameItemList.push(nameItems.language.join('&'));
        }
        if (nameItems.type != null && nameItems.type != '') {
          nameItemList.push(nameItems.type);
        }
        if (nameItems.desc != null && nameItems.desc != '') {
          nameItemList.push(nameItems.desc.trim());
        }
        return nameItemList.join('-');
      }
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ [nameItemsDesc] .el-form-item__error {
  margin-left: 48% !important;
}

.creative_request_form-body {
  width: 80%;
  margin: 0 auto;
  -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}


.creative_request_upload-body {
  width: 80%;
  margin: 10px auto;
  -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}

.refCreative {
  a {
    cursor: pointer;
  }
}

.request_creativeNum {
  /deep/ .el-input.is-disabled .el-input__inner {
    color: black;
  }
}

.creative_list {
  /deep/ .el-upload-list__item {
    text-align: center;
    vertical-align: middle;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /deep/ .el-upload-list--picture-card {
    display: flex;
    flex-wrap: wrap;
  }

  .creative {
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;
    vertical-align: middle;
  }
}

.creative-detail-list {
  .dialog-close {
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 0);
    color: white;
  }

  /deep/ .el-dialog {
    background: rgba(255, 255, 255, 0);
    -webkit-box-shadow: none;
    box-shadow: none;
  }

  /deep/ .el-dialog__header {
    padding: 0;
  }

  img {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }

  /deep/ video {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }
}

.product_Search {
  display: flex;
  flex-direction: row;
}

.product_Body {
  width: 90%;
  margin: 1em auto auto auto;

  .product_UploadDate {
    color: #00a2ff;
    font-weight: 600;
    border-bottom: solid 2px #BDC3C7;
    padding-bottom: 3px;
    padding-left: 3em;
  }

  .product_isUpload {
    margin-top: 10px;
    display: flex;

    .product_isUpload_label {
      width: 100px;
    }

    .product_isUpload_content {
      flex: 1;
      height: 240px;
      overflow: scroll;
      display: flex;
      flex-wrap: wrap;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item {
      overflow: inherit;
    }

    .product_border {
      width: 150px;
      height: 330px;
      margin-right: 10px;
      box-sizing: border-box;

      .productCreativeTest {
        font-size: 14px;
        margin: 5px;

        div {
          width: 100%;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          line-height: 2em;
        }
      }
    }
  }
}

.checkRequestHistory {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  line-height: 28px;
  padding-right: 3em;

  a {
    padding-right: 2em;
    cursor: pointer;
  }
}

.tabs_creative {
  display: flex;
  border: 1px solid rgba(22, 132, 252, 100);
  border-radius: 10px;
  text-align: center;
  width: 320px;
}

.tags_true {
  color: white;
  background: #1684FC 10000%;
}

.tags_false {
  color: #1684FD;
  background: white;
}
</style>
